package br.org.credfaz.sis.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.org.credfaz.sis.Db2ConnectionFactory;
import br.org.credfaz.sis.MysqlConnectionFactory;
import br.org.credfaz.sis.modelo.Contratomutuo;

public class AvalistaDAO {

	private final Connection connection;
	private final Connection connectionLocal;
	
 	List<Contratomutuo> contratoAvalistaGravar = new ArrayList<Contratomutuo>();
 	ContratomutuoDAO cmutuo = new ContratomutuoDAO();
	
		public AvalistaDAO() {
			try {
				connection = new Db2ConnectionFactory().getConnection();
				connectionLocal = new MysqlConnectionFactory().getConnection();
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	
		
		public void atualizaAvalista() {
			try {
				List<Contratomutuo> contratoAvalistaTce = new ArrayList<Contratomutuo>();
				List<Contratomutuo> contratoAvalistaLocal = new ArrayList<Contratomutuo>();
	
				PreparedStatement stmtTce = this.connection
						.prepareStatement("SELECT DISTINCT idcliente, NUMCONTRATOCREDITO FROM coopcons.contratocredito c WHERE EXISTS " +
								"(SELECT * FROM coopcons.GARANTIDORCENTRALRISCO g WHERE c.NUMCONTRATOCREDITO = g.DESCOPERACAO)");
				ResultSet rsTce = stmtTce.executeQuery();
	
				while (rsTce.next()) {
					contratoAvalistaTce.add(gravaAvalfinanceira(rsTce));
				}
				
				PreparedStatement stmtLocal = this.connectionLocal.prepareStatement("SELECT * FROM contratocredito");
				ResultSet rsLocal = stmtLocal.executeQuery();
				
				while (rsLocal.next()) {
					contratoAvalistaLocal.add(gravaAvalfinanceira(rsLocal));
				}
				
				for (Contratomutuo contratomutuo : contratoAvalistaLocal) {
					for (Contratomutuo contratomutuo2 : contratoAvalistaTce) {
						if (contratomutuo.getNumcontratomutuo() == contratomutuo2.getNumcontratomutuo()) {
							contratomutuo.setPossuiAvalista(true);
							cmutuo.atualizaAvalista(contratomutuo);
						}
					}
				}
				
				
				rsTce.close();
				rsLocal.close();
	
				
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	
		private Contratomutuo gravaAvalfinanceira(ResultSet rs)
				throws SQLException {
			
			Contratomutuo cmutuo = new Contratomutuo();
	
			cmutuo.setIdcliente(rs.getInt("idcliente"));
			cmutuo.setNumcontratomutuo(rs.getFloat("numcontratocredito"));
						
			return cmutuo;
		}
	

}
